// pages/petInfo/schedule/index.js
Page({
  data: {
    dateList: [], //本月日历
    nextMonthList: [], //本月日历
    todayDate: {}, //今天
    yearList:[],
    yearIndex:0,
    thisYear:new Date().getFullYear(),
    canSelect:[],
    selectDay:{},//选中的日期
  },
  today(){
    this.setMonth(new Date().getFullYear(),new Date().getMonth()+1,new Date().getDate());
  },
  //选择年
  yearChange(e){
    let month=this.data.todayDate.month;
    let dateString= this.data.yearList[e.detail.value]+'-' + (month<10?'0'+month:month)+ '-'+this.data.todayDate.day;
    let todayDate={
      dateString:dateString,
      day:this.data.todayDate.day,
      year:this.data.yearList[e.detail.value],
      month:this.data.todayDate.month,
    }
    this.setData({
      todayDate:todayDate,
      yearIndex:e.detail.value
    })
    this.getYearData()
  },
  onLoad: function (options) {
    if(options.sendWeek){
      let sendWeek=options.sendWeek;
      sendWeek=sendWeek.split(",");
      let arr=[];
      if(sendWeek.length>0){
        sendWeek.forEach(item=>{
          let obj='';
          switch (item){
            case '一':
              obj=1;
              break;
            case '二':
              obj=2;
              break;
            case '三':
              obj=3;
              break;
            case '四':
              obj=4;
              break;
            case '五':
              obj=5;
              break;
            case '六':
              obj=6;
              break;
            default :
              obj=0;
          }
          arr.push(obj)
           
        })
      }
      this.setData({
        canSelect:arr,
      })
    }
    if(options.selectDay){
      let selectDay=JSON.parse(decodeURIComponent((options.selectDay))) 
      if(selectDay.dateString!=''){
        this.setData({
          selectDay:selectDay
        })
      }
    }
    let now = new Date()
    let todayDate = {
      year: now.getFullYear(),
      month: now.getMonth() + 1,
      day: now.getDate(),
      dateString: this.formatTime(now, "Y-M-D")
    }
    let yearList=[];
    for(let i=now.getFullYear();i<now.getFullYear()+1;i++){
      yearList.push(i)
    }
    this.setData({
      todayDate:todayDate,
      yearList:yearList,
      yearIndex:yearList.length-1
    })
  },
  //获取任意时间的最后一天
  getLastDay(d){
    let date=d.replace(/-/g,'/');
    var current=new Date(date);
    var currentMonth=current.getMonth();
    var nextMonth=++currentMonth;
    var nextMonthDayOne =new Date(current.getFullYear(),nextMonth,1);
    var minusDate=1000*60*60*24;
    let lastDay=new Date(nextMonthDayOne.getTime()-minusDate);
    let month=(lastDay.getMonth()+1);
    month=month<10?'0'+month:month;
    return lastDay.getFullYear() + "-" + month + "-"+lastDay.getDate()
  },
  onReady: function () {
  },
  //获取一年的数据
  getYearData(){
    let arr=[];
    for(let i=1;i<=12;i++){
      arr.push(this.getYearDay(this.data.todayDate.year,i))
    }
    this.setData({
      yearDate:arr
    })
  },
  chooseMonth(e){
    let month=e.currentTarget.dataset.index+1;
    let dateString= this.data.todayDate.year+'-' + (month<10?'0'+month:month)+ '-'+this.data.todayDate.day;
    let todayDate={
      dateString:dateString,
      day:this.data.todayDate.day,
      year:this.data.todayDate.year,
      month:month
    }
    this.setData({
      current:1,
      todayDate:todayDate,
    })
    let date=this.data.todayDate.dateString.replace(/-/g,'/');
    this.setMonth(new Date(date).getFullYear(),new Date(date).getMonth()+1,new Date(date).getDate());
  },
  onShow: function () {
    this.setMonth(this.data.todayDate.year, this.data.todayDate.month, this.data.todayDate.day);
    
  },
  onHide: function () {

  },
  onUnload: function () {

  },
  onPullDownRefresh: function () {

  },
  onReachBottom: function () {

  },
  formatTime(time, format) {
    function formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    }

    function getDate(time, format) {
      const formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
      const returnArr = []
      const date = new Date(time)
      returnArr.push(date.getFullYear())
      returnArr.push(formatNumber(date.getMonth() + 1))
      returnArr.push(formatNumber(date.getDate()))
      returnArr.push(formatNumber(date.getHours()))
      returnArr.push(formatNumber(date.getMinutes()))
      returnArr.push(formatNumber(date.getSeconds()))
      for (const i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i])
      }
      return format
    }

    function getDateDiff(time) {
      let r = ''
      const ft = new Date(time)
      const nt = new Date()
      const nd = new Date(nt)
      nd.setHours(23)
      nd.setMinutes(59)
      nd.setSeconds(59)
      nd.setMilliseconds(999)
      const d = parseInt((nd - ft) / 86400000)
      switch (true) {
        case d === 0:
          const t = parseInt(nt / 1000) - parseInt(ft / 1000)
          switch (true) {
            case t < 60:
              r = '刚刚'
              break
            case t < 3600:
              r = parseInt(t / 60) + '分钟前'
              break
            default:
              r = parseInt(t / 3600) + '小时前'
          }
          break
        case d === 1:
          r = '昨天'
          break
        case d === 2:
          r = '前天'
          break
        case d > 2 && d < 30:
          r = d + '天前'
          break
        default:
          r = getDate(time, 'Y-M-D')
      }
      return r
    }
    if (!format) {
      return getDateDiff(time)
    } else {
      return getDate(time, format)
    }
  },
  //picker设置月份
  editMonth(e) {
    const arr = e.detail.value.split("-")
    const year = parseInt(arr[0])
    const month = parseInt(arr[1])
    this.setMonth(year, month)
  },
  //上月切换按钮点击
  lastMonth() {
    const lastMonth = new Date(this.data.todayDate.year, this.data.todayDate.month - 2)
    const year = lastMonth.getFullYear()
    const month = lastMonth.getMonth() + 1
    this.setMonth(year, month)
  },
  //下月切换按钮点击
  nextMonth() {
    const nextMonth = new Date(this.data.todayDate.year, this.data.todayDate.month)
    const year = nextMonth.getFullYear()
    const month = nextMonth.getMonth() + 1
    this.setMonth(year, month)
  },
  //设置月份
  setMonth(setYear, setMonth, setDay) {
    // if (this.data.todayDate.year !== setYear || this.data.todayDate.month !== setMonth) {
      const day = Math.min(new Date(setYear, setMonth, 0).getDate(), this.data.todayDate.day)
      const time = new Date(setYear, setMonth - 1, setDay ? setDay : day)
      const data = {
        todayDate: {
          year: setYear,
          month: setMonth,
          day: setDay ? setDay : day,
          dateString: this.formatTime(time, "Y-M-D")
        }
      }
      if (!setDay) {
        data.open = true
      }
      this.setData(data)
      this.dateInit(setYear, setMonth)
    // }
  },
  //日历主体的渲染方法
  dateInit(setYear = this.data.todayDate.year, setMonth = this.data.todayDate.month) {
    let dateList = []; //需要遍历的日历数组数据
    let nextMonthList=[];
    let now = new Date(setYear, setMonth - 1)//当前月份的1号
    let startWeek = now.getDay(); //目标月1号对应的星期
    let dayNum = new Date(setYear, setMonth, 0).getDate()//当前月有多少天
    if(startWeek==0){
      startWeek=6
    }else{
      startWeek--
    }
    let forNum = Math.ceil((startWeek + dayNum) / 7) * 7 //当前月跨越的周数
    for (let i = 0; i < forNum; i++) {
      const now2 = new Date(now)
      now2.setDate(i - startWeek + 1)
      let obj = {};
      let weekDaySelect=this.data.canSelect.findIndex(item=>item==now2.getDay())==-1?false:true ;
      let t1 = new Date(this.formatTime(now2, "Y-M-D").replace(/-/g,"/")) ;
      let t2 = new Date();
      let weekDaySelect2='';
      if(t1>=t2){
        weekDaySelect2=true;
      }else{
        weekDaySelect2=false;
      }
      let weekDaySelect3=weekDaySelect&&weekDaySelect2?true:false
      obj = {
        weekDaySelect:weekDaySelect3,
        weekDay:now2.getDay(),
        day: now2.getDate(),
        month: now2.getMonth() + 1,
        year: now2.getFullYear(),
        dateString: this.formatTime(now2, "Y-M-D")
      };
      dateList[i] = obj;
    }
    const nextMonth = new Date(this.data.todayDate.year, this.data.todayDate.month)
    const nyear = nextMonth.getFullYear()
    const nmonth = nextMonth.getMonth() + 1;
    let nnow = new Date(nyear, nmonth - 1)//当前月份的1号
    let nstartWeek = nnow.getDay(); //目标月1号对应的星期
    let ndayNum = new Date(nyear, nmonth, 0).getDate()//当前月有多少天
    if(nstartWeek==0){
      nstartWeek=6
    }else{
      nstartWeek--
    }
    let nforNum = Math.ceil((nstartWeek + ndayNum) / 7) * 7 //当前月跨越的周数
    for (let i = 0; i < nforNum; i++) {
      const now2 = new Date(nnow)
      now2.setDate(i - nstartWeek + 1)
      let obj = {};
      obj = {
        weekDaySelect:this.data.canSelect.findIndex(item=>item==now2.getDay())==-1?false:true ,
        weekDay:now2.getDay(),
        day: now2.getDate(),
        month: now2.getMonth() + 1,
        year: now2.getFullYear(),
        dateString: this.formatTime(now2, "Y-M-D")
      };
      nextMonthList[i] = obj;
    }
    let nextselectDay = {
      year:nyear,
      month:nmonth,
    }
    this.setData({
      nextselectDay:nextselectDay,
      dateList: dateList,
      nextMonthList:nextMonthList
    })
  },
  getYearDay(setYear,setMonth){
    let dateList = []; //需要遍历的日历数组数据
    let now = new Date(setYear, setMonth - 1)//当前月份的1号
    let startWeek = now.getDay(); //目标月1号对应的星期
    let dayNum = new Date(setYear, setMonth, 0).getDate()//当前月有多少天
    if(startWeek==0){
      startWeek=6
    }else{
      startWeek--
    }
    let forNum = Math.ceil((startWeek + dayNum) / 7) * 7 //当前月跨越的周数
    for (let i = 0; i < forNum; i++) {
      const now2 = new Date(now)
      now2.setDate(i - startWeek + 1)
      let obj = {};
      obj = {
        day: now2.getDate(),
        month: now2.getMonth() + 1,
        year: now2.getFullYear(),
        dateString: this.formatTime(now2, "Y-M-D")
      };
      dateList[i] = obj;
    }
    return dateList
  },
  //点击本月
  selectChange(e) {
    if(e.currentTarget.dataset.year==this.data.todayDate.year&&e.currentTarget.dataset.month===this.data.todayDate.month){//点击本月日期
      if(this.data.dateList[e.currentTarget.dataset.index].weekDaySelect){//选择可选的日期
        this.setData({
          selectDay:this.data.dateList[e.currentTarget.dataset.index]
        })
        this.setPreData()
      }
      
    }
    // const year = e.currentTarget.dataset.year
    // const month = e.currentTarget.dataset.month
    // const day = e.currentTarget.dataset.day
    // const dateString = e.currentTarget.dataset.dateString
    // const todayDate = {
    //   year: year,
    //   month: month,
    //   day: day,
    //   dateString: dateString
    // }
    // if(dateString==this.data.todayDate.dateString)return
    // if (this.data.todayDate.year !== year || this.data.todayDate.month !== month) {
    //   this.setMonth(year, month, day)
    // } else if (this.data.todayDate.day !== day) {
    //   this.setData({
    //     todayDate: todayDate
    //   })
    // }
  },
  selectNextMday(e){
    if(e.currentTarget.dataset.year==this.data.nextselectDay.year&&e.currentTarget.dataset.month===this.data.nextselectDay.month){//点击本月日期
      if(this.data.nextMonthList[e.currentTarget.dataset.index].weekDaySelect){//选择可选的日期
        this.setData({
          selectDay:this.data.nextMonthList[e.currentTarget.dataset.index]
        })
        this.setPreData()
      }
    }
  },
  //设置上页面的配送时间
  setPreData(){
    var pages = getCurrentPages();
    // 上一页面栈
    var prevPage = pages[pages.length - 2]; 
    prevPage.setData({
      selectDay:this.data.selectDay
    });
    wx.navigateBack()
  }
})